import { HubConnection, HubConnectionBuilder } from '@microsoft/signalr';
// store.ts
import { defineStore } from 'pinia';

export const useSignalRStore = defineStore({
  actions: {
    async sendMessage(message: string) {
      if (this.hubConnection) {
        await this.hubConnection.send('message', message);
      }
    },
    async setupSignalR(url: string) {
      if (!this.hubConnection) {
        this.socketUrl = url;
        this.hubConnection = new HubConnectionBuilder().withUrl(url).build();

        await this.hubConnection.start();
      }
    },
    async stopSignalR() {
      if (this.hubConnection) {
        this.hubConnection.off('message');
        await this.hubConnection.stop();
      }
    },
  },
  id: 'signalr',
  state: () => ({
    hubConnection: null as HubConnection | null,
    socketUrl: '',
  }),
});
